package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mySun
 * @create 2021-07-13 13:49
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService  {
    //注入中间表
    private final CategoryBrandService categoryBrandService;

    public CategoryServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public List<CategoryDTO> queryCategoryByBrandId(Long brandId) {
        //获取brandId对应的中间表信息
        List<CategoryBrand> categoryBrandList = categoryBrandService.list(new QueryWrapper<CategoryBrand>().eq("brand_id", brandId));
        //判断是否有信息
        if(CollectionUtils.isEmpty(categoryBrandList)){
            return Collections.emptyList();
        }
        //找出中间表中的所有分类id
        List<Long> categoryIds = categoryBrandList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());

        List<Category> categories = this.listByIds(categoryIds);
        return CategoryDTO.convertEntityList(categories);

    }

    @Override
    public List<CategoryDTO> queryCategoryByParentId(Long pid) {
        List<Category> categoryList = this.list(new QueryWrapper<Category>().eq("parent_id", pid));
        return CategoryDTO.convertEntityList(categoryList);
    }
}
